const app = require("../app");
const { getUserByName } = require("../service/user.service");
const md5password = require("../utils/handle-password");

class LoginMiddleWare {
  // 验证登录
  async verifyAuth(ctx, next) {
    // console.log(ctx.request.body);
    // 拿到登录请求账号
    let { name, password } = ctx.request.body;
    // console.log(ctx.request.body);

    // 判断是否为空
    if (!name || !password) {
      return ctx.app.emit("error", new Error("空的账号或者密码"), ctx);
    }
    // 判断是否注册过
    const userInfo = await getUserByName(name);
    try {
      if (!userInfo[0].name === name) {
        return ctx.app.emit("error", new Error("用户名不存在"), ctx);
      }
    } catch {
      return ctx.app.emit("error", new Error("用户名不存在"), ctx);
    }

    //验证账号密码
    const password2 = md5password(password + "");
    // console.log(password2);

    if (userInfo[0].password === password2) await next();
    else return ctx.app.emit("error", new Error("密码不正确"), ctx);
  }
}

module.exports = new LoginMiddleWare();
